<template>
  <div>
    <div class="container" v-if="!addShow && !addShows">
      <Breadcrumb />
      <a-card class="data-card">
        <a-row>
          <a-col :flex="1">
            <a-form
              :model="formModel"
              :label-col-props="{ span: 6 }"
              :wrapper-col-props="{ span: 18 }"
            >
              <a-row :gutter="20">
                <a-col :span="5">
                  <a-form-item field="patientName" label="姓名">
                    <a-input
                      v-model="formModel.patientName"
                      placeholder="请输入姓名"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="5">
                  <a-form-item field="patientSex" label="性别">
                    <a-select
                      v-model="formModel.patientSex"
                      :options="sexs"
                      placeholder="请选择性别"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item field="treatment" label="是否治疗">
                    <a-select
                      v-model="formModel.treatment"
                      :options="treatments"
                      placeholder="请选择"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="5">
                  <a-space :size="18">
                    <a-button type="primary" @click="onPageChange(1)">
                      <template #icon>
                        <icon-search />
                      </template>
                      搜索
                    </a-button>
                    <a-button @click="reset">
                      <template #icon>
                        <icon-refresh />
                      </template>
                      重置
                    </a-button>
                  </a-space>
                </a-col>
              </a-row>
            </a-form>
          </a-col>
        </a-row>
        <a-divider style="margin-top: 0" />
        <a-row style="margin-bottom: 16px">
          <a-col :span="12">
            <a-space>
              <a-button @click="openAdd" type="primary">
                <template #icon>
                  <icon-plus />
                </template>
                新增
              </a-button>
              <a-button @click="openUpload"> 批量导入 </a-button>
            </a-space>
          </a-col>
          <a-col
            :span="12"
            style="display: flex; align-items: center; justify-content: end"
          >
            <!-- <a-space>
              <a-button @click="downloadUser">
                <template #icon>
                  <icon-download />
                </template>
                批量导出
              </a-button>
            </a-space> -->
          </a-col>
        </a-row>
        <a-table
          ref="userList"
          row-key="userId"
          v-model:selectedKeys="userIds"
          :loading="loading"
          page-position="bottom"
          :pagination="pagination"
          :row-selection="rowSelection"
          :columns="columns"
          :data="renderData"
          :bordered="false"
          @page-change="onPageChange"
          @page-size-change="onPageSizeChange"
        >
          <template #sex="{ record }">
            <template v-for="(item, index) in sexs">
              <span v-if="record.patientSex == item.value">{{
                item.label
              }}</span>
            </template>
          </template>
          <template #treatment="{ record }">
            <span>{{ record.treatment ? '是' : '否' }}</span>
          </template>
          <template #option="{ record }">
            <a-space :size="18">
              <div @click="openEdit(record)" class="zdivbot">个人信息</div>
              <div @click="openEdits(record)" class="zdivbot">预约详情</div>
              <div
                @click="openDelete(record)"
                v-if="record.username != 'admin'"
                class="zdivbotdel"
              >
                删除</div
              >
            </a-space>
          </template>
        </a-table>
      </a-card>

      <a-modal
        v-model:visible="uploadShow"
        @cancel="uploadCancel"
        :on-before-ok="uploadCheck"
        :mask-closable="false"
        unmountOnClose
        width="450px"
      >
        <template #title> 导入用户 </template>
        <a-form ref="uploadModel" :rules="uploadRules" :model="uploadForm">
          <a-row style="margin-bottom: 16px">
            <!-- <a-form-item field="roleId" label="角色">
            <a-select
              v-model="uploadForm.roleId"
              :options="roles"
              :field-names="rolesFields"
              placeholder="请选择角色"
            />
          </a-form-item> -->

            <a-form-item field="file" label="文件">
              <a-upload
                class="upload_box"
                @change="onChange"
                accept=".xls,.xlsx"
                ref="uploadRef"
                :auto-upload="false"
                :limit="1"
              >
                <template #upload-button>
                  <a-space>
                    <a-button type="primary">选择附件</a-button>
                    <a-button @click.stop="downloadTemplate">下载模板</a-button>
                  </a-space>
                </template>
              </a-upload>
            </a-form-item>
          </a-row>
        </a-form>
      </a-modal>
    </div>
    <!-- 患者信息录入 信息编辑 -->
    <div class="container" v-if="addShow">
      <a-card title="患者信息">
        <a-form ref="addModel" :rules="rules" :model="addForm">
          <a-row style="display: flex !important">
            <a-col :span="8">
              <a-form-item field="patientName" label="姓名">
                <a-input
                  v-model="addForm.patientName"
                  size="large"
                  placeholder="请输入姓名"
                  :disabled="addForm.patientId ? true : false"
                ></a-input> </a-form-item
            ></a-col>
            <a-col :span="8"
              ><a-form-item field="idCard" label="身份证号">
                <a-input
                  v-model="addForm.idCard"
                  size="large"
                  placeholder="请输入身份证号"
                  :disabled="addForm.patientId ? true : false"
                /> </a-form-item
            ></a-col>
            <a-col :span="8">
              <a-form-item field="patientSex" label="性别">
                <a-select
                  v-model="addForm.patientSex"
                  :options="sexs"
                  placeholder="请选择性别"
                /> </a-form-item
            ></a-col>
          </a-row>
          <a-row style="display: flex !important; flex-flow: nowrap">
            <a-form-item field="patientAge" label="患者年龄">
              <a-input
                v-model="addForm.patientAge"
                size="large"
                placeholder="请输入患者年龄"
              />
            </a-form-item>
            <a-form-item field="mobile" label="手机号">
              <a-input
                v-model="addForm.mobile"
                size="large"
                placeholder="请输入手机号"
              />
            </a-form-item>
            <a-form-item field="bedNumber" label="床位号">
              <a-select
                v-model="addForm.bedNumber"
                :options="bedNumbers"
                placeholder="请选择床位号"
                allow-search
              />
            </a-form-item>
          </a-row>
          <a-row style="display: flex !important; flex-flow: nowrap">
            <a-form-item field="remark" label="备注">
              <a-input
                v-model="addForm.remark"
                size="large"
                placeholder="请输入备注"
              />
            </a-form-item>
            <a-form-item></a-form-item>
            <a-form-item></a-form-item>
          </a-row>
        </a-form>
      </a-card>

      <!-- 保存患者信息 -->
      <div class="addhz">
        <a-button type="primary" status="success" @click="handleCheck"
          >保存患者信息</a-button
        >
        <a-button type="primary" status="warnin" @click="handleCancel"
          >返回</a-button
        >
      </div>
    </div>
    <!--预约详情-->
    <div class="container" v-if="addShows">
      <a-card title="患者信息">
        <a-form ref="addModel" :rules="rules" :model="addForm">
          <a-row style="display: flex !important">
            <a-col :span="8">
              <a-form-item field="patientName" label="姓名">
                <a-input
                  v-model="addForm.patientName"
                  size="large"
                  placeholder="请输入姓名"
                  :disabled="addForm.patientId ? true : false"
                ></a-input> </a-form-item
            ></a-col>
            <a-col :span="8"
              ><a-form-item field="idCard" label="身份证号">
                <a-input
                  v-model="addForm.idCard"
                  size="large"
                  placeholder="请输入身份证号"
                  :disabled="addForm.patientId ? true : false"
                /> </a-form-item
            ></a-col>
            <a-col :span="8">
              <a-form-item field="patientSex" label="性别">
                <a-select
                  v-model="addForm.patientSex"
                  :options="sexs"
                  placeholder="请选择性别"
                  :disabled="addForm.patientId ? true : false"
                /> </a-form-item
            ></a-col>
          </a-row>
          <a-row style="display: flex !important; flex-flow: nowrap">
            <a-form-item field="patientAge" label="患者年龄">
              <a-input
                v-model="addForm.patientAge"
                size="large"
                placeholder="请输入患者年龄"
                :disabled="addForm.patientId ? true : false"
              />
            </a-form-item>
            <a-form-item field="mobile" label="手机号">
              <a-input
                v-model="addForm.mobile"
                size="large"
                placeholder="请输入手机号"
                :disabled="addForm.patientId ? true : false"
              />
            </a-form-item>
            <a-form-item field="bedNumber" label="床位号">
              <a-select
                v-model="addForm.bedNumber"
                :options="bedNumbers"
                placeholder="请选择床位号"
                allow-search
                :disabled="addForm.patientId ? true : false"
              />
            </a-form-item>
          </a-row>
          <a-row style="display: flex !important; flex-flow: nowrap">
            <a-form-item field="remark" label="备注">
              <a-input
                v-model="addForm.remark"
                size="large"
                placeholder="请输入备注"
                :disabled="addForm.patientId ? true : false"
              />
            </a-form-item>
            <a-form-item></a-form-item>
            <a-form-item></a-form-item>
          </a-row>
        </a-form>
      </a-card>
      <a-card title="治疗信息" v-if="!addShowxm">
        <div class="addzlitembox">
          <div class="addzlitembutton" @click="addzlxmshow = true">添加</div>

          <div class="addzlbox">
            <a-table
              ref="userList"
              row-key="userId"
              v-model:selectedKeys="userIds"
              :loading="loading"
              page-position="bottom"
              :pagination="paginations"
              :show-header="false"
              :columns="columnss"
              :data="renderDataxm"
              @page-change="onPageChanges"
              @page-size-change="onPageSizeChanges"
            >
              <template #patientTreatmentId="{ record }">
                <div class="addzlitem" @click="goRecord(record)">
                  <div class="addzlitemdes"
                    >接待部门：{{ record.groupName }}/{{
                      record.attribute
                    }}</div
                  >
                  <div class="addzlitemdes"
                    >开始时间：{{ record.startDate }}</div
                  >
                  <div class="addzlitemdes">治疗次数：{{ record.number }}</div>
                  <div class="addzlitemdes" @click.stop
                    >是否治疗：
                    <a-switch
                      style="z-index: 999"
                      @change="xmdisable($event, record)"
                      :checked-value="1"
                      :unchecked-value="9"
                      v-model="record.disabled"
                    />
                  </div>
                </div>
              </template>
            </a-table>
          </div>
        </div>
      </a-card>
      <!--  -->
      <!-- 保存患者信息 -->
      <div class="addhz" v-if="!addShowxm">
        <a-button type="primary" status="warnin" @click="handleCancel"
          >返回</a-button
        >
      </div>
      <!-- 治疗记录 -->
      <div>
        <a-row
          ><a-col :span="12">
            <a-card title="治疗记录" v-if="addShowxm">
              <a-row>
                <a-col :flex="1">
                  <a-form
                    :model="formModels"
                    :label-col-props="{ span: 6 }"
                    :wrapper-col-props="{ span: 18 }"
                  >
                    <div class="csddf">
                      <a-form-item field="nickname" label="治疗师">
                        <a-input
                          v-model="formModels.nickname"
                          placeholder="请输入治疗师姓名"
                          allow-clear
                        />
                      </a-form-item>

                      <a-form-item field="type" label="开始日期">
                        <!-- <a-date-picker
                          show-time
                          format="YYYY-MM-DD"
                          v-model="formModels.startDate"
                        /> -->
                        <a-range-picker
                          v-model="formModels.Date"
                          style="width: 310px; margin: 0 24px 24px 0"
                          format="YYYY-MM-DD"
                        />
                      </a-form-item>

                      <!-- <a-form-item field="type" label="结束日期">
                        <a-date-picker
                          show-time
                          format="YYYY-MM-DD"
                          v-model="formModels.endDate"
                        />
                      </a-form-item> -->

                      <!-- <a-form-item field="type" label="治疗进度">
                        <a-select
                          v-model="formModels.type"
                          :options="types"
                          placeholder="请选择"
                          allow-clear
                        />
                      </a-form-item> -->
                      <div>
                        <a-space :size="18">
                          <a-button type="primary" @click="onPageChangejl(1)">
                            <template #icon>
                              <icon-search />
                            </template>
                            搜索
                          </a-button>
                          <a-button @click="resetjl">
                            <template #icon>
                              <icon-refresh />
                            </template>
                            重置
                          </a-button>
                        </a-space>
                      </div>
                    </div>
                  </a-form>
                </a-col>
              </a-row>
              <div class="addzlitemboxs">
                <div class="addzlbox">
                  <a-table
                    ref="userList"
                    row-key="userId"
                    v-model:selectedKeys="userIds"
                    :loading="loading"
                    page-position="bottom"
                    :pagination="paginationjl"
                    :show-header="false"
                    :columns="columnjl"
                    :data="renderDatajl"
                    :bordered="false"
                    @page-change="onPageChangejl"
                    @page-size-change="onPageSizeChangejl"
                  >
                    <template #treatmentPlanId="{ record }">
                      <div class="addzlitem">
                        <div
                          :class="record.signStatus == 9 ? 'status' : 'statuss'"
                        ></div>
                        <div>预约时间：{{ record.planTime }}</div>
                        <div>治疗师：{{ record.nickname }}</div>
                        <!-- <div class="zdivbot" @click="goEvaluation(record)"
                          >治疗详情</div
                        > -->
                        <!-- <div>预约时间:{{ record.evaluation }}</div> -->
                      </div>
                    </template>
                  </a-table>
                </div>
              </div>
            </a-card></a-col
          >
          <a-col :span="12">
            <a-card title="治疗评判" v-if="addShowxm">
              <div class="addzlitemboxss">
                <div class="addzlbox">
                  <a-table
                    ref="userList"
                    row-key="userId"
                    v-model:selectedKeys="userIds"
                    :loading="loading"
                    page-position="bottom"
                    :pagination="paginationpp"
                    :show-header="false"
                    :columns="columnpp"
                    :data="renderDatapp"
                    :bordered="false"
                    @page-change="onPageChangepp"
                    @page-size-change="onPageSizeChangepp"
                  >
                    <template #title="{ record }">
                      <div class="addzlitem">
                        <div class="pgtitle">评估名称：{{ record.title }}</div>
                        <div>创建时间：{{ record.createTime }}</div>
                        <div>评估用户：{{ record.createUser }}</div>
                        <div class="zdivbot" @click="goEvaluation(record)"
                          >查看</div
                        >
                        <!-- <div>预约时间:{{ record.evaluation }}</div> -->
                      </div>
                    </template>
                  </a-table>
                </div>
              </div>
            </a-card></a-col
          >
        </a-row>
      </div>
      <!--  返回上一级 -->
      <div class="addhz" v-if="addShowxm">
        <a-button type="primary" status="warnin" @click="backxm">返回</a-button>
      </div>
    </div>
    <!-- 添加治疗记录弹窗 -->
    <a-modal
      v-model:visible="addzlxmshow"
      @cancel="handleCancels"
      :on-before-ok="handleChecks"
      :mask-closable="false"
      unmountOnClose
      width="500px"
    >
      <template #title> 治疗项目</template>
      <a-form ref="addModels" :rules="ruless" :model="addFormzlxm">
        <a-form-item field="startDate" label="开始日期">
          <a-date-picker format="YYYY-MM-DD" v-model="addFormzlxm.startDate" />
        </a-form-item>
        <a-form-item field="groupNamezh" label="组织管理">
          <a-cascader
            v-model="addFormzlxm.groupNamezh"
            :max-tag-count="1"
            :options="organizations"
            placeholder="请选择组织"
            @change="changsd"
            :field-names="organizationsFields"
          ></a-cascader>
        </a-form-item>
      </a-form>
    </a-modal>
    <!-- 治疗评判 -->
    <a-modal
      v-model:visible="Evaluationshow"
      @cancel="Evaluationshowfn"
      :mask-closable="false"
      unmountOnClose
      width="auto"
    >
      <template #title>评估详情</template>
      <div class="tjpgmianbox">
        <div class="pglibox">
          <!-- 组件 -->
          <ShangzhiPg
            ref="pgb"
            :patientTreatmentId="patientTreatmentId"
            :Evaluationshow="Evaluationshow"
            :Evaluationdata="Evaluationdata"
            v-if="pgtitle == '上肢功能评估量表 UEFI'"
          />
          <CuizhongPg
            :Evaluationshow="Evaluationshow"
            ref="pgb"
            :Evaluationdata="Evaluationdata"
            :patientTreatmentId="patientTreatmentId"
            v-if="pgtitle == '美国国立卫生研究院卒中量表'"
          />
          <JisuiPg
            :Evaluationshow="Evaluationshow"
            ref="pgb"
            :Evaluationdata="Evaluationdata"
            :patientTreatmentId="patientTreatmentId"
            v-if="pgtitle == '脊髓损伤积分评定表'"
          />
          <YiyuPg
            ref="pgb"
            :Evaluationshow="Evaluationshow"
            :Evaluationdata="Evaluationdata"
            :patientTreatmentId="patientTreatmentId"
            v-if="pgtitle == '汉密尔顿抑郁表'"
          />
          <JiaolvPg
            ref="pgb"
            :Evaluationshow="Evaluationshow"
            :Evaluationdata="Evaluationdata"
            :patientTreatmentId="patientTreatmentId"
            v-if="pgtitle == '汉密尔顿焦虑量表'"
          />
          <GuanjieyanPg
            ref="pgb"
            :Evaluationshow="Evaluationshow"
            :Evaluationdata="Evaluationdata"
            :patientTreatmentId="patientTreatmentId"
            v-if="pgtitle == 'WOMAC骨性关节炎指数评分表'"
          />
          <MmssPg
            ref="pgb"
            :Evaluationshow="Evaluationshow"
            :Evaluationdata="Evaluationdata"
            :patientTreatmentId="patientTreatmentId"
            v-if="pgtitle == 'MMSE评分量表'"
          />
          <HuodongPg
            ref="pgb"
            :Evaluationshow="Evaluationshow"
            :Evaluationdata="Evaluationdata"
            :patientTreatmentId="patientTreatmentId"
            v-if="pgtitle == 'ICF活动和参与评价量表'"
          />
          <HunmiPg
            ref="pgb"
            :Evaluationshow="Evaluationshow"
            :Evaluationdata="Evaluationdata"
            :patientTreatmentId="patientTreatmentId"
            v-if="pgtitle == 'Glasgow昏迷量表（安亭）'"
          />
          <YundongPg
            ref="pgb"
            :Evaluationshow="Evaluationshow"
            :Evaluationdata="Evaluationdata"
            :patientTreatmentId="patientTreatmentId"
            v-if="pgtitle == 'Fugl-Meyer运动功能评分法'"
          />
          <BrunnstromPg
            ref="pgb"
            :Evaluationshow="Evaluationshow"
            :Evaluationdata="Evaluationdata"
            :patientTreatmentId="patientTreatmentId"
            v-if="pgtitle == 'Brunnstrom分期'"
          />
          <!--  -->
          <!--  -->
        </div>
      </div>
      <!-- <div class="zlbox">
        <div class="table">
          <div class="row">
            <div class="cell cellpjt">治疗师信息</div>
            <div class="cell colspan-4 divd">
              <div
                >分组:{{ Evaluationjc.groupName }}-{{
                  Evaluationjc.attribute
                }}</div
              >
              <div>治疗师:{{ Evaluationjc.nickname }}</div>
            </div>
          </div>
          <div class="row">
            <div class="cell cellpjt">综合评判</div>
            <div class="cell colspan-4">{{ Evaluationdata.evaluation }}</div>
          </div>

          <div v-for="(item, index) in Evaluationdata.list" :key="index">
            <div class="row">
              <div class="cell colspan-4">治疗内容项目</div>
              <div class="cell cellpj">优秀</div>
              <div class="cell cellpj">良好</div>
              <div class="cell cellpj">较差</div>
            </div>
            <div class="row">
              <div class="cell colspan-4">{{ item.content }}</div>
              <div class="cell cellpj"
                ><icon-check style="color: green" v-if="item.good == 1"
              /></div>
              <div class="cell cellpj"
                ><icon-check style="color: green" v-if="item.poor == 1"
              /></div>
              <div class="cell cellpj"
                ><icon-check style="color: green" v-if="item.good == 1"
              /></div>
            </div>
          </div>
        </div>
      </div> -->
    </a-modal>
  </div>
</template>
<script lang="ts">
  export default {
    name: 'user',
  };
</script>
<script lang="ts" setup>
  import { computed, ref, reactive, watch, nextTick } from 'vue';
  import useLoading from '@/hooks/loading';
  import { useSelectionStore } from '@/store';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  import { Message, Modal } from '@arco-design/web-vue';
  import {
    adminUserListpatient,
    patientSave,
    patientUpdate,
    patientRemove,
    resetPassword,
    importpatient,
    adminUserExport,
    downloadTemplate,
    schemeList,
    patientTreatmentAdd,
    patientTreatmentSwitch,
    patientTreatmentRecordList,
    patientTreatmentEvaluation,
    evaluationList,
  } from '@/api/patient';
  //   import { deptTree } from '@/api/dept.ts';
  import { organizationTree } from '@/api/organization';
  import { roleList } from '@/api/role';
  import { values } from 'lodash';
  import { Notification } from '@arco-design/web-vue';
  import ShangzhiPg from '@/components/pingu/shangzhiPg.vue';
  import CuizhongPg from '@/components/pingu/cuizhongPg.vue';
  import JisuiPg from '@/components/pingu/jisuiPg.vue';
  import YiyuPg from '@/components/pingu/yiyuPg.vue';
  import JiaolvPg from '@/components/pingu/jiaolvPg.vue';
  import GuanjieyanPg from '@/components/pingu/guanjieyanPg.vue';
  import MmssPg from '@/components/pingu/mmssPg.vue';
  import HuodongPg from '@/components/pingu/huodongPg.vue';
  import HunmiPg from '@/components/pingu/hunmiPg.vue';
  import YundongPg from '@/components/pingu/yundongPg.vue';
  import BrunnstromPg from '@/components/pingu/BrunnstromPg.vue';
  //   import { majorTree } from '@/api/major.ts';
  const Evaluationshow = ref<boolean>(false);
  const pgtitle = ref('');
  const Evaluationshowfn = () => {
    pgtitle.value = '';
    Evaluationshow.value = false;
  };
  const Evaluationdata = ref([]);

  const Evaluationjc = ref({
    nickname: '',
    groupName: '',
    attribute: '',
  });
  // 治疗详情
  const goEvaluation = (item: any) => {
    pgtitle.value = item.title;
    Evaluationjc.value.nickname = item.nickname;
    if (item.evaluationId) {
      // console.log('已平板');

      patientTreatmentEvaluation({
        evaluationId: item.evaluationId,
      }).then((res: any) => {
        if (res.code == 200) {
          Evaluationdata.value = JSON.parse(res.data);
          console.log('查询评估详情成功', Evaluationdata.value);
          Evaluationshow.value = true;
        }
      });
    } else {
      Notification.warning({
        title: '提示',
        content: '当前治疗暂无评判！',
      });
    }
  };
  // 诊疗记录列表
  const goRecord = (item: any) => {
    patientTreatmentId.value = item.patientTreatmentId;
    Evaluationjc.value = item;
    addShowxm.value = true;
    fetchDatajl();
    fetchDatapp();
    // console.log('执行力');
  };
  const changsd = (value: any) => {
    addFormzlxm.value.groupName = '';
    addFormzlxm.value.attribute = '';
    function findParentIdById(idToFind: any) {
      for (let i = 0; i < organizations.value.length; i++) {
        const item: any = organizations.value[i];
        if (item.id === idToFind) {
          return item.parentId;
        }
        if (item.children) {
          for (let j = 0; j < item.children.length; j++) {
            const childItem = item.children[j];
            if (childItem.id === idToFind) {
              return item.id;
            }
            if (childItem.children) {
              for (let k = 0; k < childItem.children.length; k++) {
                const grandChildItem = childItem.children[k];
                if (grandChildItem.id === idToFind) {
                  return childItem.id;
                }
              }
            }
          }
        }
      }
      return null;
    }
    const parentId = findParentIdById(value);
    addFormzlxm.value.groupName = parentId;
    addFormzlxm.value.attribute = value;
    //   formModel.value.attribute = value;
    // formModel.value.groupName = parentId;
    // if (parentId == 0) {
    //   formModel.value.attribute = '';
    //   formModel.value.groupName = value;
    // }
    // console.log('巅峰', value, parentId);
  };
  // 治疗项目是否开启
  const xmdisable = (value: any, item: any) => {
    console.log('改变的值', value, item);
    patientTreatmentSwitch({
      patientTreatmentId: item.patientTreatmentId,
      disabled: value,
      groupName: item.groupNameId,
      attribute: item.attributeId,
      startDate: item.startDate,
      patientId: addForm.value.patientId,
    }).then((res: any) => {
      if (res.code == 200) {
        fetchDatas();
      }
    });
  };
  // 治疗项目
  const addzlxmshow = ref(false);
  const { loading, setLoading } = useLoading(true);

  const generateDataModel = () => {
    return {
      patientId: '',
      patientName: '',
      patientSex: '',
      idCard: '',
      patientAge: '',
      mobile: '',
      remark: '',
      bedNumbers: '',
    };
  };
  const ruless = {
    groupNamezh: [
      {
        required: true,
        message: '请选择组织',
      },
    ],
    startDate: [
      {
        required: true,
        message: '请选择开始日期',
      },
    ],
  };
  const rules = {
    idCard: [
      {
        required: true,
        message: '请输入身份证号',
      },
    ],
    patientName: [
      {
        required: true,
        message: '请输入姓名',
      },
    ],
    patientAge: [
      {
        required: true,
        message: '请输入年龄',
      },
    ],
    patientSex: [
      {
        required: true,
        message: '请选择性别',
      },
    ],
  };
  const addFormzlxm = ref({
    groupNamezh: '',
    groupName: '',
    attribute: '',
    startDate: '',
    patientId: '',
  });
  const addForm = ref(generateDataModel());
  const addShow = ref(false);
  const addShows = ref(false);
  const addModel = ref();

  const openAdd = () => {
    addForm.value = generateDataModel();
    addShow.value = true;
  };

  const handleCheck = () => {
    if (loading.value) {
      return;
    }
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 1500);
    addModel.value.validate(
      async (errors: undefined | Record<string, ValidatedError>) => {
        if (!errors) {
          if (addForm.value.patientId) {
            patientUpdate(addForm.value).then((res: any) => {
              if (res.code == '200') {
                Message.success({
                  content: res.message,
                });

                reset();
                handleCancel();
              } else {
              }
            });
          } else {
            patientSave(addForm.value).then((res: any) => {
              if (res.code == '200') {
                Message.success({
                  content: res.message,
                });

                reset();
                handleCancel();
              } else {
                handleCancel();
              }
            });
          }
        } else {
          // handleCancel();
        }
      }
    );
  };
  const addModels = ref();
  const handleChecks = (done: any) => {
    if (loading.value) {
      done(false);
      return;
    }
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 1500);
    addModels.value.validate(
      async (errors: undefined | Record<string, ValidatedError>) => {
        if (!errors) {
          patientTreatmentAdd(addFormzlxm.value).then((res: any) => {
            if (res.code == '200') {
              Message.success({
                content: res.message,
              });
              done(true);
              fetchDatas();
              addFormzlxm.value.startDate = '';
              addFormzlxm.value.groupNamezh = '';
            } else {
              done(false);
            }
          });
        } else {
          done(false);
        }
      }
    );
  };

  const openEdit = (item: any) => {
    console.log('当前个人信息', item);

    addForm.value = item;
    addShow.value = true;
  };
  const openEdits = (item: any) => {
    addForm.value = item;
    addShows.value = true;
    addFormzlxm.value.patientId = item.patientId;
    fetchDatas();
  };
  const renderDataxm = ref([]);
  const fetchDatas = () => {
    schemeList({
      patientId: addFormzlxm.value.patientId,
      pageNum: paginations.current,
      ...paginations,
    }).then((res: any) => {
      if (res.code == 200) {
        renderDataxm.value = res.data.list;
        // renderDataxm.value.map((item) => {
        //   item.disabled = item.disabled.toString();
        //   return item;
        // });
        paginations.total = res.data.total;
        paginations.current = res.data.pageNum;
        console.log('查询治疗项目列表成功', res.data.list);
      }
    });
  };
  const handleCancels = () => {
    addzlxmshow.value = false;
  };
  const handleCancel = () => {
    addShow.value = false;
    addShows.value = false;
  };
  const addShowxm = ref(false);
  const backxm = () => {
    addShowxm.value = false;
  };
  const openDelete = (item: any) => {
    Modal.confirm({
      title: '提示',
      content: '确认删除吗？',
      onOk() {
        patientRemove({
          patientId: item.patientId,
        }).then((res: any) => {
          if (res.code == '200') {
            Message.success({
              content: res.message,
            });
            fetchData();
          }
        });
      },
    });
  };
  const openRePass = (item: any) => {
    Modal.confirm({
      title: '提示',
      content: '确认重置此用户密码吗？',
      onOk() {
        resetPassword({
          userId: item.userId,
        }).then((res: any) => {
          if (res.code == '200') {
            Message.success({
              content: res.message,
            });
          }
        });
      },
    });
  };

  const generateLockModel = () => {
    return {
      userIds: '',
      effectiveTime: '',
    };
  };
  const lockForm = ref(generateLockModel());

  const lockShow = ref(false);
  const lockModel = ref();
  const userIds = ref([]);

  const openUnlock = (item: any) => {
    lockForm.value = {
      ...generateLockModel(),
      userIds: item.userId,
    };
    lockShow.value = true;
  };

  const generateUploadModel = () => {
    return {
      file: '',
      deptId: '',
      roleId: '',
      effectiveTime: '',
      majorIds: '',
      majorIdsArr: [],
    };
  };

  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  });
  const columns = computed<TableColumnData[]>(() => [
    { title: '录入时间', dataIndex: 'createTime' },
    {
      title: '患者姓名',
      dataIndex: 'patientName',
    },
    {
      title: '患者id',
      dataIndex: 'idCard',
    },
    {
      title: '性别',
      dataIndex: 'patientSex',
      slotName: 'sex',
      align: 'center',
    },
    {
      title: '年龄',
      dataIndex: 'patientAge',
    },
    {
      title: '床位号',
      dataIndex: 'bedNumber',
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
    },
    {
      title: '治疗记录',
      dataIndex: 'treatmentNumber',
      align: 'center',
    },
    {
      title: '是否治疗中',
      dataIndex: 'treatment',
      slotName: 'treatment',
      align: 'center',
    },

    {
      title: '安排治疗',
      dataIndex: 'option',
      slotName: 'option',
      align: 'center',
    },
  ]);
  const columnss = computed<TableColumnData[]>(() => [
    {
      title: '插槽',
      dataIndex: 'patientTreatmentId',
      slotName: 'patientTreatmentId',
    },
  ]);
  const columnjl = computed<TableColumnData[]>(() => [
    {
      title: '插槽',
      dataIndex: 'treatmentPlanId',
      slotName: 'treatmentPlanId',
    },
  ]);
  const columnpp = computed<TableColumnData[]>(() => [
    {
      title: '插槽',
      dataIndex: 'title',
      slotName: 'title',
    },
  ]);

  const sexs = useSelectionStore().sexs;

  const treatments = ref([
    {
      value: 'true',
      label: '是',
    },
    {
      value: 'false',
      label: '否',
    },
  ]);
  const types = ref([
    {
      value: 'YES',
      label: '已结束',
    },
    {
      value: 'NO',
      label: '未结束',
    },
  ]);
  const generateFormModel = () => {
    return {
      patientName: '',
      patientSex: '',
      treatment: '',
    };
  };

  const formModel = ref(generateFormModel());

  const formModels = ref({
    nickname: '',
    startDate: '',
    endDate: '',
    type: '',
    Date: '',
  });
  const renderData = ref([]);
  const userList = ref();

  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
    total: 0,
  };
  const pagination = reactive({
    ...basePagination,
    'hide-on-single-page': true,
    'show-total': true,
    'show-jumper': true,
    'show-page-size': true,
  });
  const paginations = reactive({
    'current': 1,
    'pageSize': 6,
    'total': 0,
    'hide-on-single-page': true,
    'show-total': true,
    'show-jumper': true,
    'show-page-size': true,
  });
  const paginationjl = reactive({
    'current': 1,
    'pageSize': 10,
    'total': 0,
    'hide-on-single-page': true,
    'show-total': true,
    'show-jumper': true,
    'show-page-size': true,
  });
  const paginationpp = reactive({
    'current': 1,
    'pageSize': 10,
    'total': 0,
    'hide-on-single-page': true,
    'show-total': true,
    'show-jumper': true,
    'show-page-size': true,
  });

  const fetchData = async () => {
    setLoading(true);
    try {
      const data = {
        pageNum: pagination.current,
        ...pagination,
        ...formModel.value,
      };
      adminUserListpatient(data).then((res: any) => {
        let list = res.data.list || [];
        list.map((item: any) => {
          item.disabled = item.isLocking == 1 ? false : true;
        });
        renderData.value = list;
        pagination.total = res.data.total;
        pagination.current = res.data.pageNum;
        userList.value.selectAll(false);
      });
    } catch (err) {
      console.log(err);
    } finally {
      setLoading(false);
    }
  };
  const renderDatajl = ref([]);
  const patientTreatmentId = ref('');
  const fetchDatajl = async () => {
    setLoading(true);
    try {
      console.log('当前日期', formModels.value);

      formModels.value.startDate = formModels.value.Date[0];
      formModels.value.endDate = formModels.value.Date[1];
      // formModels.value.Date = null;
      const data = {
        pageNum: paginationjl.current,
        ...paginationjl,
        ...formModels.value,
        patientTreatmentId: patientTreatmentId.value,
      };
      patientTreatmentRecordList(data).then((res: any) => {
        let list = res.data.list || [];

        renderDatajl.value = list;
        paginationjl.total = res.data.total;
        paginationjl.current = res.data.pageNum;
        userList.value.selectAll(false);
      });
    } catch (err) {
      console.log(err);
    } finally {
      setLoading(false);
    }
  };
  const renderDatapp = ref();
  const fetchDatapp = async () => {
    setLoading(true);
    try {
      const data = {
        pageNum: paginationpp.current,
        ...paginationpp,
        patientTreatmentId: patientTreatmentId.value,
      };
      evaluationList(data).then((res: any) => {
        let list = res.data.list || [];
        renderDatapp.value = list;
        paginationpp.total = res.data.total;
        paginationpp.current = res.data.pageNum;
        // userList.value.selectAll(false);
      });
    } catch (err) {
      console.log(err);
    } finally {
      setLoading(false);
    }
  };
  //
  const onPageChange = (current: number) => {
    pagination.current = current;
    fetchData();
  };
  const onPageChangejl = (current: number) => {
    paginationjl.current = current;
    fetchDatajl();
  };
  const onPageChangepp = (current: number) => {
    paginationpp.current = current;
    fetchDatapp();
  };
  const onPageSizeChangepp = (pageSize: number) => {
    paginationpp.pageSize = pageSize;
    fetchDatapp();
  };
  const onPageSizeChangejl = (pageSize: number) => {
    paginationjl.pageSize = pageSize;
    fetchDatajl();
  };
  const onPageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    fetchData();
  };
  const onPageChanges = (current: number) => {
    paginations.current = current;
    fetchDatas();
  };
  const onPageSizeChanges = (pageSize: number) => {
    paginations.pageSize = pageSize;
    fetchDatas();
  };

  const reset = () => {
    formModel.value = generateFormModel();
    fetchData();
  };
  const resetjl = () => {
    formModels.value = {
      nickname: '',
      startDate: '',
      endDate: '',
      type: '',
      Date: '',
    };
    fetchDatajl();
  };
  fetchData();

  const downloadUser = () => {
    adminUserExport(formModel.value).then((res: any) => {});
  };

  const roles = ref([]);
  const rolesFields = {
    value: 'roleId',
    label: 'roleName',
  };

  const organizations = ref([]);
  const organizationsFields = {
    value: 'id',
    label: 'name',
  };
  const uploadRules = {
    file: [
      {
        required: true,
        message: '请选择附件',
      },
    ],
  };
  const uploadForm = ref(generateUploadModel());
  const uploadShow = ref(false);
  const uploadModel = ref();
  const openUpload = () => {
    uploadForm.value = generateDataModel();
    uploadShow.value = true;
  };
  const uploadCheck = (done: any) => {
    if (loading.value) {
      done(false);
      return;
    }
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 1500);
    uploadModel.value.validate(
      async (errors: undefined | Record<string, ValidatedError>) => {
        if (!errors) {
          let formData = new FormData();
          // formData.append('deptId', uploadForm.value.deptId);
          // formData.append('roleId', uploadForm.value.roleId);
          // formData.append('effectiveTime', uploadForm.value.effectiveTime);
          // formData.append('majorIds', uploadForm.value.majorIds);
          formData.append('file', uploadForm.value.file);
          importpatient(formData).then((res: any) => {
            if (res.code == '200') {
              Message.success({
                content: res.message,
              });
              reset();
              done(true);
            } else {
              done(false);
            }
          });
        } else {
          done(false);
        }
      }
    );
  };
  const uploadCancel = () => {
    uploadShow.value = false;
  };
  const onChange = (fileList: any) => {
    if (fileList && fileList.length > 0) {
      uploadForm.value.file = fileList[0].file;
    } else {
      uploadForm.value.file = null;
    }
  };
  const getOrganizations = () => {
    organizationTree().then((res: any) => {
      organizations.value = res.data || [];
    });
  };
  getOrganizations();

  // 动态生成 bedNumbers 数组
  const generateBedNumbers = () => {
    const bedNumbers = [];

    // 添加 1-1 到 1-60
    for (let i = 1; i <= 60; i++) {
      bedNumbers.push({
        label: `1-${i}`,
        value: `1-${i}`,
      });
    }

    // 添加 2-1 到 2-20
    for (let i = 1; i <= 20; i++) {
      bedNumbers.push({
        label: `2-${i}`,
        value: `2-${i}`,
      });
    }

    return bedNumbers;
  };

  // 使用 ref 创建响应式数据
  const bedNumbers = ref(generateBedNumbers());
</script>
<style scoped>
  .pgtitle {
    width: 300px;
  }
  .tjpgmianbox {
    display: flex;
    flex-direction: column;
    max-height: 620px;
    max-width: 1200px;
  }
  .pglibox {
    margin: 10px 0;
  }
  .pgselectbox {
    margin: 0px auto;
  }
</style>
